﻿using Kingdee.BOS;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.Core.SqlBuilder;
using Kingdee.BOS.JSON;
using Kingdee.BOS.Log;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.WebApi.FormService;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;

namespace Caraya.MFG.BusinessPlugIn
{
    /// <summary>
    /// 执行计划
    /// Caraya.MFG.BusinessPlugIn.PurPdfService,Caraya.MFG.BusinessPlugIn
    /// </summary>
    public class PurPdfService : IScheduleService
    {
        public void Run(Context ctx, Schedule schedule)
        {
            string param1 = schedule.Parameters;
            string formId = schedule.ParameterFormId;
            try
            {
                if (string.IsNullOrEmpty(param1)) return;
                if (string.IsNullOrEmpty(formId)) return;
                var tmpParam = param1?.Split(',');
                if (tmpParam != null)
                {
                    for (int i = 0; i < tmpParam.Length; i++)
                    {
                        if (string.IsNullOrEmpty(tmpParam[i])) continue;
                        var strSQL = $"SELECT count(1) FROM T_BAS_ATTACHMENT WHERE FBILLTYPE='{formId}'and FINTERID={tmpParam[i]}";
                        var attaCount = DBServiceHelper.ExecuteScalar(ctx, strSQL, 0);
                        if (attaCount > 0)
                        {
                            UpdateScheduleService(ctx, schedule, tmpParam[i]);
                            continue;
                        }
                        var businessData = LoadBillObject(ctx, formId, tmpParam[i]);
                        if (businessData == null)
                        {
                            UpdateScheduleService(ctx, schedule, tmpParam[i]);
                            continue;
                        }
                        // 这里应该根据参数获取对应文件url和名称
                        var pdfUrl = "https://wx.g127.com:9008/UploadFiles/background.jpg";
                        var pdfName = "1.jpg";

                        string base64EncodedData = ExecuteWebRequest(pdfUrl);
                        var AttObject = new JSONObject();
                        AttObject.Put("FileName", pdfName);
                        AttObject.Put("FormId", formId);
                        AttObject.Put("IsLast", true);
                        AttObject.Put("InterId", tmpParam[i]);
                        AttObject.Put("BillNO", businessData["BillNo"]);
                        AttObject.Put("AliasFileName", pdfName);
                        AttObject.Put("SendByte", base64EncodedData);
                        Dictionary<string, object> result = (Dictionary<string, object>)WebApiServiceCall.AttachmentUpload(ctx, AttObject.ToJSONString());
                        var resultObj = result["Result"] as Dictionary<string, object>;
                        var responseStatusObj = resultObj["ResponseStatus"] as Dictionary<string, object>;
                        bool isSuccess = (bool)responseStatusObj["IsSuccess"];
                        if (isSuccess)
                        {
                            UpdateScheduleService(ctx, schedule, tmpParam[i]);
                        }
                    }
                }
                //var strSQL = "SELECT count(1) FROM T_BAS_ATTACHMENT WHERE FBILLTYPE='PUR_PurchaseOrder'and (FINTERID=100005 or FBILLNO='CGDD000003') and FATTACHMENTNAME='1.jpg'";
                //var attaList = DBServiceHelper.ExecuteScalar(ctx, strSQL, 0);
                //if (attaList > 0)
                //{
                //    Logger.Error("EVENT", "附件已存在，本次跳过", null);
                //    return;
                //}
                //var pdfUrl = "https://wx.g127.com:9008/UploadFiles/background.jpg";
                //var pdfName = "1.jpg";

                //string base64EncodedData = ExecuteWebRequest(pdfUrl);
                //var AttObject = new JSONObject();
                //AttObject.Put("FileName", pdfName);
                //AttObject.Put("FormId", "PUR_PurchaseOrder");
                //AttObject.Put("IsLast", true);
                //AttObject.Put("InterId", 100005);
                //AttObject.Put("BillNO", "CGDD000003");
                //AttObject.Put("AliasFileName", pdfName);
                //AttObject.Put("SendByte", base64EncodedData);
                //Dictionary<string, object> result = (Dictionary<string, object>)WebApiServiceCall.AttachmentUpload(ctx, AttObject.ToJSONString());
                //var json = JsonConvert.SerializeObject(result);
                ////var webapi = new K3CloudApi();
                ////webapi.InitClient("61271b176f110c", "217311_Q6dO67sGTmmUQ5TKT27q7yXvzq2U5AOP", "b53e78db1bae4f859e2acb0de4d52552", "test", 2052, "100", "http://localhost:1200/k3cloud/");
                ////var result = webapi.Execute<Repo>("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.AttachmentUpLoad", new object[] { AttObject });
                ////if (!result.Result.ResponseStatus.IsSuccess)
                ////{
                ////    throw new Exception(result.Result.ResponseStatus.Errors[0].Message);
                ////}
                //var resultObj = result["Result"] as Dictionary<string, object>;
                //var responseStatusObj = resultObj["ResponseStatus"] as Dictionary<string, object>;
                //bool isSuccess = (bool)responseStatusObj["IsSuccess"];
                //if (!isSuccess)
                //{
                //    var errorsObj = GetErrorMessages(responseStatusObj);
                //    var errCode = responseStatusObj["ErrorCode"];
                //    var msgCode = responseStatusObj["MsgCode"];
                //    var message = new StringBuilder();
                //    foreach (var msg in errorsObj)
                //    {
                //        message.AppendLine(msg);
                //    }
                //    throw new Exception($"errCode:{errCode},msgCode:{msgCode} - {message}");
                //}
                //var FileIdObj = (string)responseStatusObj["FileId"];
                //Logger.Error("EVENT", "附件上传成功，FileId：" + FileIdObj, null);
            }
            catch (Exception ex)
            {
                Logger.Error("EVENT", "上传错误：" + ex.Message, ex);
            }
        }

        /// <summary>
        /// 更新执行计划参数
        /// </summary>
        private void UpdateScheduleService(Context ctx, Schedule schedule, string pkId)
        {
            if (string.IsNullOrEmpty(pkId)) return;
            var strSQL = $"SELECT FPARAMETERS FROM T_BAS_SCHEDULEINFO WHERE (FSCHEDULEID = '{schedule.ScheduleId}')";
            var param0 = DBServiceHelper.ExecuteScalar(ctx, strSQL, "");
            var param2 = param0.Split(',');
            var match = param2.Where(t => !t.Contains(pkId)).ToArray();
            strSQL = $"UPDATE T_BAS_SCHEDULEINFO SET FPARAMETERS = '{string.Join(",", match)}' WHERE (FSCHEDULEID = '{schedule.ScheduleId}')";
            var res = DBServiceHelper.Execute(ctx, strSQL);
            Debug.WriteLine(res);
        }

        static List<string> GetErrorMessages(Dictionary<string, object> dict)
        {
            List<string> errorMessages = new List<string>();
            if (dict.TryGetValue("Errors", out object errorsObj))
            {
                if (errorsObj is List<object> errorsList)
                {
                    foreach (var errorItem in errorsList)
                    {
                        if (errorItem is Dictionary<string, object> errorDict && errorDict.TryGetValue("Message", out object messageObj))
                        {
                            if (messageObj is string message)
                            {
                                errorMessages.Add(message);
                            }
                        }
                    }
                }
            }
            return errorMessages;
        }
        /// <summary>
        /// 将下载文件转化为Base64字符串形式
        /// </summary>
        public static string ExecuteWebRequest(string url)
        {
            Uri uri = new Uri(url);
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
            using (WebResponse response = httpWebRequest.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        responseStream.CopyTo(memoryStream);
                        byte[] fileData = memoryStream.ToArray();
                        return Convert.ToBase64String(fileData);
                    }
                }
            }
        }

        private DynamicObject LoadBillObject(Context ctx, string formId, object number)
        {
            FormMetadata meta = MetaDataServiceHelper.Load(ctx, formId) as FormMetadata;
            var queryParam = new QueryBuilderParemeter();
            queryParam.FormId = formId;
            queryParam.BusinessInfo = meta.BusinessInfo;
            queryParam.FilterClauseWihtKey = string.Format("{0} = '{1}' ", meta.BusinessInfo.GetForm().PkFieldName, number);
            var bdObjs = BusinessDataServiceHelper.Load(ctx, meta.BusinessInfo.GetDynamicObjectType(), queryParam);
            if (bdObjs.Length == 0) return null;
            return bdObjs[0];
        }
    }
}
